package com.zzyl.framework.interceptor;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Administrator
 * @version 1.0
 * @description: TODO
 * @date 2025/9/13 18:44
 */
@Component
public class MemberInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1、从请求头中获取 token
        String token = request.getHeader("authorization");

        // 2、判断token是否存在，不存在直接返回401
        if(ObjectUtil.isEmpty(token)){
            responseTokenParseFail(response,"token为空，认证失败！");
        }

        // 3、解析token，如果解析失败直接返回401
        Claims claims = null;
        try {
            claims = tokenService.parseToken(token);
        } catch (Exception e) {
            responseTokenParseFail(response,"token不合法，解析失败！");
        }

        // 4、从token中获取 userId，如果获取不到，直接返回401
        Long userId = MapUtil.getLong(claims, "userId");
        if(ObjectUtil.isNull(userId)){
            responseTokenParseFail(response,"获取不到用户id，认证失败！");
        }

        // 5、如果取到了，把userId存入ThreadLocal
        UserThreadLocal.set(userId);

        // 6、放行
        return true;
    }

    private static void responseTokenParseFail(HttpServletResponse response,String message) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        throw new BaseException(message);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}